from django_redis import get_redis_connection
from rest_framework import serializers
from redis import RedisError
import logging

logger = logging.getLogger('django')

class ImageCodeCheckSerializer(serializers.Serializer):
    '''
    图片验证码序列器
    '''
    image_code_id = serializers.UUIDField()
    text = serializers.CharField(max_length=4,min_length=4)
    def validate(self, attrs):
        '''
        校验
        '''
        image_code_id = attrs['image_code_id']
        text = attrs['text']
        # 指明redis存储地址
        redis_conn = get_redis_connection('verify_codes')
        image_code_server = redis_conn.get('img_%s' % image_code_id)

        if image_code_server is None:
            raise serializers.ValidationError('无效的图片验证码')

        try:
            redis_conn.delete('img_%s' % image_code_id)
        except RedisError as e:
            logger.error(e)

        image_code_server = image_code_server.decode()
        if text.lower() !=  image_code_server.lower():
            raise serializers.ValidationError('输入验证码有误')

        #校验60s内是否重复发送短信
        # 学习如何在序列化器中获取请求传入到试图中的额外的数据
        mobile = self.context['view'].kwargs['mobile']
        send_flag = redis_conn.get('send_flag_%s' % mobile)
        if send_flag:
            raise serializers.ValidationError('发送短信验证码过于频繁')
        return attrs